/**
 * 
 */
package com.asset.salesforce.controller.pages;

import java.util.ArrayList;
import java.util.List;
import java.util.Random;

import javax.mail.internet.MimeMessage;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.crypto.hash.Sha256Hash;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import com.asset.salesforce.domain.Employee;
import com.asset.salesforce.domain.JoinRequest;
import com.asset.salesforce.domain.Role;
import com.asset.salesforce.domain.User;
import com.asset.salesforce.service.EmployeeService;
import com.asset.salesforce.service.JobTitleService;
import com.asset.salesforce.service.JoinRequestService;
import com.asset.salesforce.service.RoleShiroService;
import com.asset.salesforce.service.UserShiroService;

// TODO: Auto-generated Javadoc
/**
 * The Class RequestController.
 *
 * @author Hisham
 */
@Controller
public class RequestController {
	
	/** The employee service. */
	@Autowired
	private EmployeeService employeeService;
	
	/** The job title service. */
	@Autowired
	private JobTitleService jobTitleService;
	
	/** The join request service. */
	@Autowired
	private JoinRequestService joinRequestService;
	
	/** The user shiro service. */
	@Autowired
	private UserShiroService userShiroService;

	/** The role shiro service. */
	@Autowired
	private RoleShiroService roleShiroService;
	
	/** The mail sender. */
	@Autowired
	private JavaMailSender mailSender;

	/**
	 * Gets the leads page.
	 *
	 * @param session the session
	 * @param model the model
	 * @param response the response
	 * @return the leads page
	 */
	@RequestMapping(value = "/pendingRequest", method = RequestMethod.GET)
	public String getLeadsPage(HttpSession session, Model model,HttpServletResponse response) {
		if (null == session.getAttribute("userDetails")) {return "redirect:login";}
		if (SecurityUtils.getSubject().hasRole("owner")){
			Employee employee = (Employee) session.getAttribute("userDetails");
			List<JoinRequest> joinRequests = joinRequestService.getJoinRequestByOwnerId(employee.getId());
			model.addAttribute("joinRequests", joinRequests);
			return "requestPage";
		}
		else{
			return "accessDenied";					
		}
	}
	
	/**
	 * Refuse joinrequest.
	 *
	 * @param session the session
	 * @param model the model
	 * @param request the request
	 * @return the string
	 */
	@RequestMapping(value = "/refuseRequests", method = RequestMethod.GET)
	public String refuseJoinrequest(HttpSession session, Model model,HttpServletRequest request) {
		Integer id = Integer.parseInt(request.getParameter("id").toString());
		JoinRequest joinRequest = joinRequestService.getById(id);
		joinRequest.setStatus(2);
		joinRequestService.saveOrupdate(joinRequest);
		Employee userDetails = (Employee) session.getAttribute("userDetails");
		model.addAttribute("userDetails", userDetails);
		return "redirect:pendingRequest";
	}
	
	/**
	 * Accept joinrequest.
	 *
	 * @param session the session
	 * @param model the model
	 * @param request the request
	 * @return the string
	 */
	@RequestMapping(value = "/acceptRequests", method = RequestMethod.GET)
	public String acceptJoinrequest(HttpSession session, Model model,HttpServletRequest request) {
		Integer id = Integer.parseInt(request.getParameter("id").toString());
		Integer empId = Integer.parseInt(request.getParameter("empId").toString());
		Employee employee = employeeService.getById(empId);
		if (employee != null) {
			JoinRequest joinRequest = joinRequestService.getById(id);
			joinRequest.setStatus(1);
			joinRequestService.saveOrupdate(joinRequest);
			employee.setIsActive(true);
			employeeService.saveOrupdate(employee);
			User user = new User();
			user.setEmail(employee.getEmail());
			Random random = new Random();
			Integer password = random.nextInt(12345678);
			user.setPassword(new Sha256Hash(password.toString()).toHex());
			user.setUsername(employee.getNickName());
			user.setCompanyId(employee);
			
			List<Role> roles = new ArrayList<Role>();
			Role role = new Role();
			String jobTitle = employee.getJobTitle().getName();
			if (jobTitle != null) {
				if (jobTitle.equals("Lead Generator")) {
					role = roleShiroService.findRole("leadgenerator");
				} else if (jobTitle.equals("Sales Manager")) {
					role = roleShiroService.findRole("salesmanager");
				} else if (jobTitle.equals("Sales Man")) {
					role = roleShiroService.findRole("salesman");
				} else if (jobTitle.equals("Bussiness Devlivery")) {
					role = roleShiroService.findRole("bussinessdeveloper");
				}
			}
			roles.add(role);
			user.setRoles(roles);
			userShiroService.addUser(user);
			
			String toAddress = employee.getEmail();
			String txt = "<div style='font-family: verdana,arial,sans-serif; font-size: 12px; color: rgb(85, 85, 85);  border: 1px solid rgb(0, 0, 0); width: 550px; height: 370px; background: none repeat scroll 0% 0% rgb(255, 255, 255); box-shadow: 0px 0px 15px rgb(204, 204, 204);'>"
					+ "<h4 style='margin: 0px 0px 10px 0px; width: 530px; background: none repeat scroll 0% 0% rgb(0, 0, 0); font-size: 17px; font-weight: bold; padding: 10px; color: rgb(242, 242, 242);'>Asset Group CRM</h4>"
					+ "<h5 style='margin: 0 10px; padding: 0px; font-size: 12px;'>Hi "
					+ employee.getfName()
					+ ",</h5>"
					+ "<br/>"
					+ "<p style='margin: 0 10px; text-align: justify; line-height: 20px; padding: 0;'>Thanks for joining Asset Group CRM that's fast, efficient and maybe even fun.</p>"
					+ "<br/>"
					+ "<p style='margin: 0 10px; text-align: justify; line-height: 20px; padding: 0;'>Your request to join "
					+ employee.getfName()
					+ " company is accepted and your account has been created � now it will be easier than ever to share and connect with your co-workers.</p>"
					+ "<br/>"
					+ "<p style='margin: 0 10px; text-align: justify; line-height: 20px; padding: 0;'>You can login now with your email:"
					+ "<br/><span style='margin: 0 10px; font-weight: bold; color: rgb(0, 0, 0);'>"
					+ employee.getEmail()
					+ "</span>"
					+ "<br/>and password:"
					+ "<br/><span style='margin: 0 10px; font-weight: bold; color: rgb(0, 0, 0);'> "
					+ password.toString()
					+ "</span></p>"
					+ "<br/>"
					+ "<p style='margin: 0 10px; text-align: justify; line-height: 20px; padding: 0;'>To complete the sign-up process, please follow this link to set a new password:</p>"
					+ "<br/>"
					+ "<a href='http://192.168.1.10:8080/sales/login.html' style='margin: 0 10px; float: left; clear: both; color: #0067E7;'>http://192.168.1.10:8080/sales/login.html</a>"
					+ "<br/>"
					+ "<span style='margin: 0 10px 7px; float: left; clear: both; padding: 0;'>Thanks,</span>"
					+ "<br/>"
					+ "<span style='margin: 0 10px 15px; float: left; clear: both; padding: 0;'>Asset Group CRM Team.</span>"
					+ "</div>";
			MimeMessage message = mailSender.createMimeMessage();
			try {
				MimeMessageHelper helper = new MimeMessageHelper(message, true);
				helper.setTo(toAddress);
				helper.setSubject("Agile Group CRM Registeration confirmation ");
				helper.setText(txt, true);
			} catch (Exception e) {
				e.printStackTrace();
			}
			mailSender.send(message);
			return "redirect:pendingRequest";
		} else {
			return "login";
		}

	}
}
